package com.ruoyi.framework.web.service.proxy;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.token.UserDirectToken;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;

import java.util.Objects;

/**
 * @author ab785
 * createTime: 2021-10-22.
 * description: 登录流抽象类
 */
public abstract class LoginFlow {

    /**
     * 根据登录类型获取登陆流
     */
    public static LoginFlow getInstance(String loginType) {
        //用户名密码登录
        if (Objects.equals(loginType, UserConstants.LOGIN_TYPE_USER_NAME)) {
            return new UserNameLoginFlow();
        }
        //手机号验证码登录
        if (Objects.equals(loginType, UserConstants.LOGIN_TYPE_PHONE_CODE)) {
            return new PhoneLoginFlow();
        }
        //微信验证码登录
        if (Objects.equals(loginType, UserConstants.LOGIN_TYPE_WECHAT_CODE)) {
            return new WechatCodeLoginFlow();
        }
        //微信扫码
        if (Objects.equals(loginType, UserConstants.LOGIN_TYPE_WECHAT_SCAN)) {
            return new WechatScanLoginFlow();
        }
        return null;
    }

    /**
     * 校验验证码
     *
     * @param loginBody 登录请求体
     */
    abstract void checkCaptcha(LoginBody loginBody);

    /**
     * 登陆前校验内容
     *
     * @param loginBody 登录请求体
     */
    protected void checkPre(LoginBody loginBody) {
        //校验IP
        String blackStr = SpringUtils.getBean(ISysConfigService.class).selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 校验redis中存储的验证码，checkCaptcha的redis实现
     */
    protected void checkRedisCapture(LoginBody loginBody, String verifyKey) {
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        String captcha = redisCache.getCacheObject(verifyKey);
        //验证码失效或未发送
        if (StrUtil.isEmpty(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        //验证码已失效
        if (!loginBody.getCode().equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        //验证成功后删除验证码
        redisCache.deleteObject(verifyKey);
    }

    /**
     * 执行登录
     *
     * @param loginBody 登录请求体
     * @return 登录返回权限信息
     */
    abstract Authentication doLogin(LoginBody loginBody);

    /**
     * 使用用户名直接登录，用于使用用户名快速登录调用
     */
    protected Authentication userNameDirectLogin(LoginBody loginBody) {
        UserDirectToken userDirectToken = new UserDirectToken(loginBody.getUsername());
        AuthenticationContextHolder.setContext(userDirectToken);

        AuthenticationManager authenticationManager = SpringUtils.getBean(AuthenticationManager.class);
        return authenticationManager.authenticate(userDirectToken);
    }

    /**
     * TODO 登录成功事件
     */
    protected void onLoginSuccess(LoginUser loginUser) {
        System.out.println(";;;登录完成回调====");
    }

    /**
     * 执行登录流程
     *
     * @param loginBody 登录请求体
     * @return 登陆成功的token
     */
    public String execFlow(LoginBody loginBody) {

        /*第一步 校验登录验证码*/
        checkCaptcha(loginBody);

        /*IP校验*/
        checkPre(loginBody);


        /*第二部 执行登录*/
        Authentication authentication = null;
        try {
            authentication = doLogin(loginBody);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        System.out.println("=========登录完成");
        /* 第三步 获取登录返回信息 */
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        /* 登录成功事件 */
        onLoginSuccess(loginUser);

        /* 登录成功记录 */
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        /* 最后，记录登录结果*/
        ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
        SysUser user = loginUser.getUser();
        user.setLoginIp(IpUtils.getIpAddr());
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);

        //返回token
        TokenService tokenService = SpringUtils.getBean(TokenService.class);
        return tokenService.createToken(loginUser);

    }
}
